import base64
import json
import pickle

from django import http
from django.http import HttpResponseBadRequest, JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
# from apps.verifications import constants
from utils import constants
from utils.response_code import RETCODE


class CartsView(View):
    """购物车管理"""

    def get(self, request):
        """添加购物车"""
        # 接收参数
        # json_dict = json.loads(request.body.decode())
        print(1111111)

        sku = SKU.objects.all()
        for sku1 in sku:
            sku_id = sku1.id
            print(sku_id)
            # count = request.GET.get('count')
            # print(count)
            selected = request.GET.get('selected', True)
            print(111111)
            # 判断参数是否齐全
            if not all([sku_id]):
                return HttpResponseBadRequest('缺少必传参数')
            # 判断sku_id是否存在
            try:
                SKU.objects.get(id=sku_id)
            except SKU.DoesNotExist:
                return HttpResponseBadRequest('商品不存在')
            # 判断count是否为数字
            try:
                count = 1
            except Exception:
                return HttpResponseBadRequest('参数count有误')
            # 判断selected是否为bool值
            if selected:
                if not isinstance(selected, bool):
                    return HttpResponseBadRequest('参数selected有误')
            print(222222)
            # 判断用户是否登录
            user = request.user
            if user.is_authenticated:
                # 用户已登录，操作redis购物车
                redis_conn = get_redis_connection('carts')
                pl = redis_conn.pipeline()
                # 新增购物车数据
                pl.hincrby('carts_%s' % user.id, sku_id, count)
                # 新增选中的状态
                if selected:
                    pl.sadd('selected_%s' % user.id, sku_id)
                # 执行管道
                pl.execute()
                # 响应结果
                return JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            else:
                # 用户未登录，操作cookie购物车
                cart_str = request.COOKIES.get('carts')
                # 如果用户操作过cookie购物车
                if cart_str:
                    # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                    cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
                else:  # 用户从没有操作过cookie购物车
                    cart_dict = {}

                # 判断要加入购物车的商品是否已经在购物车中,如有相同商品，累加求和，反之，直接赋值
                if sku_id in cart_dict:
                    # 累加求和
                    origin_count = cart_dict[sku_id]['count']
                    count += origin_count
                cart_dict[sku_id] = {
                    'count': count,
                    'selected': selected
                }
                # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
                cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
                print(3333333)
                # 创建响应对象
                response = JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str, max_age=constants.CARTS_COOKIE_EXPIRES)
                return response


class CartsShopView(View):
    """购物车管理"""

    def get(self, request):
        """展示购物车"""
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询redis购物车
            redis_conn = get_redis_connection('carts')
            # 获取redis中的购物车数据
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 获取redis中的选中状态
            cart_selected = redis_conn.smembers('selected_%s' % user.id)

            # 将redis中的数据构造成跟cookie中的格式一致，方便统一查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            # 用户未登录，查询cookies购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            # 构造购物车渲染数据
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str(cart_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
            })

            # 渲染购物车页面
        return render(request, 'shopping_cart.html', {"cart_skus": cart_skus})


class DeleteView(View):
    def get(self, request):
        """删除购物车"""
        # 接收和校验参数
        # 接收参数
        # json_dict = json.loads(request.body.decode())
        # sku_id = json_dict.get('sku_id')
        # print(sku_id)

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=1)
        except SKU.DoesNotExist:
            return http.HttpResponseBadRequest('商品不存在')
        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户未登录，删除redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 删除键，就等价于删除了整条记录
            pl.hdel('carts_%s' % user.id, 1)
            pl.srem('selected_%s' % user.id, 1)
            pl.execute()

            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return render(request, 'shopping_cart.html')
        else:
            # 用户未登录，删除cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转为bytes,再将bytes转为base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            # 创建响应对象
            response = render(request, 'shopping_cart.html')
            if 1 in cart_dict:
                del cart_dict[1]
                cookie_cart_str = base64.b64decode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('carts', cookie_cart_str, max_age=constants.CARTS_COOKIE_EXPIRES)
            return response
